package leetcode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FlattenNestedList {

	private interface NestedInteger {
		// @return true if this NestedInteger holds a single integer, rather
		// than a nested list.
		public boolean isInteger();

		// @return the single integer that this NestedInteger holds, if it holds
		// a single integer
		// Return null if this NestedInteger holds a nested list
		public Integer getInteger();

		// @return the nested list that this NestedInteger holds, if it holds a
		// nested list
		// Return null if this NestedInteger holds a single integer
		public List<NestedInteger> getList();
	}
	
	public class NestedIterator implements Iterator<Integer> {

	    private List<NestedInteger> nestedList;
	    
	    private List<Integer> list = new ArrayList<Integer>();
	    private Iterator<Integer> iterator;
	    
	    public NestedIterator(List<NestedInteger> nestedList) {
	        this.nestedList = nestedList;
	        createList();
	        iterator = list.iterator();
	    }

	    public void createList(){
	    	help(nestedList, 0);
	    }
	    
	    public void help(List<NestedInteger> nestedList, int start){
	    	int length = nestedList.size();
	    	if(start >= length){
	    	    return;
	    	}
	    	for (int i = start; i < length; i++) {
	    	    if(nestedList.get(i).isInteger()){
	    		    list.add(nestedList.get(i).getInteger());
	    	    }else{
				    help(nestedList.get(i).getList(), 0);
	    	    }
			}
	    }

		@Override
		public boolean hasNext() {
			return iterator.hasNext();
		}

		@Override
		public Integer next() {
			return iterator.next();
		}

	    
//	    @Override
//	    public Integer next() {
//	        NestedInteger ni = nestedList.get(cur);
//	        if(ni.isInteger() ){
//	            cur++;
//	            return ni.getInteger();
//	        }else{
//	            list = ni.getList();
//	            iterator = new NestedIterator(list);
//	            while(iterator.hasNext() ){
//	                return iterator.next();
//	            }
//	        }
//	    }
//
//	    @Override
//	    public boolean hasNext() {
//	        if(cur < length){
//	            if(!nestedList.get(cur).isInteger() ){
//	                list = ni.getList();
//	                iterator = new NestedIterator(list);
//	            }else{
//	                cur++;
//	            }
//	            return true;
//	        }else if(cur == legth){
//	            if(!nestedList.get(cur).isInteger() ){
//	                list = nestedList.get(cur).getList();
//	                iterator = new NestedIterator(list);
//	                return hasNext();
//	            }else{
//	                return false;
//	            }
//	        }
//	    }
	}
} 
